package com.jingyuan.client;

import com.jingyuan.common.entity.packet.HeartBeatPacket;
import com.jingyuan.common.entity.packet.MessageType;
import com.jingyuan.common.entity.utils.LocalAddressUtil;
import io.netty.channel.Channel;

import java.net.UnknownHostException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class HeartBeatScheduleJob {
    private static HeartBeatScheduleJob job=new HeartBeatScheduleJob();
    private ScheduledThreadPoolExecutor executor;
    public static HeartBeatScheduleJob getHearBeatScheduleJob(){
        return job;
    }

    public void startSchedule(Channel channel){
        //每两秒发送一次心跳报文
        this.executor=(ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if(channel.isOpen()){
                    HeartBeatPacket heartBeatPacket=new HeartBeatPacket();
                    heartBeatPacket.setMsgType(MessageType.HEARTBEAT);
                    try {
                        heartBeatPacket.setAddress(LocalAddressUtil.getLocalAddress().getHostAddress());
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    channel.writeAndFlush(heartBeatPacket);
                }
            }
        },0,2,TimeUnit.SECONDS);
    }

    public void shutdown(){
        if(!executor.isShutdown()){
            executor.shutdown();
        }
    }
}
